<template>
    <div>
        <div class="formLayout createLevel">
            <el-row class="rows basic">
                <el-col :sm="12" :md="8" :lg="6">
                    <div class="items" ref="level">
                        <label class="label" for="">
                            <img class="required" src="@/assets/img/flower_red.png" alt="">
                            级别
                        </label>
                        <el-select class="input-cont" placeholder="请选择级别" v-model="level" size='small' :disabled="isDisabled">
                            <el-option v-for="item in LvOptionsArr" :label="item" :value="item" :key="item" />
                        </el-select>
                    </div>
                </el-col>
                <el-col :sm="12" :md="8" :lg="6">
                    <div class="items" ref="name">
                        <label class="label" for="">
                            <img class="required" src="@/assets/img/flower_red.png" alt="">
                            等级名称
                        </label>
                        <el-input class="input-cont" placeholder="请输入等级名称" v-model="name" size='small' />
                    </div>
                </el-col>
                <el-col :sm="12" :md="8" :lg="6">
                    <div class="items">
                        <label class="label" for="">
                            <img class="required" src="@/assets/img/flower_red.png" alt="">
                            成长值
                        </label>
                        <el-input class="input-cont" placeholder="请输入成长开始值" ref="growthValueBegin" v-model="growthValueBegin" size='small' />
                        -
                        <el-input class="input-cont" placeholder="请输入成长结束" ref="growthValueEnd" v-model="growthValueEnd" size='small' />
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <div class="boxes">
                        <label class="label" for="">
                            <img class="required" src="@/assets/img/flower_red.png" alt="">
                            会员权益
                        </label>
                        <el-checkbox-group
                            v-model="rights"
                            class='optionsField'
                        >
                            <el-checkbox 
                                v-for="(item,index) in rightsList" 
                                :label="item.id"
                                :key="index"
                            >
                                {{item.name}}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <div class="items" style="margin-top: 1rem;">
                        <label class="label" for="">
                            <img class="required" src="@/assets/img/flower_red.png" alt="">
                            上传图片
                        </label>
                        <div class="detialCell upload" v-if="isShowUpBtn">
                            <p>+</p>
                            <input class="upfile" type="file" @change="upfileChange($event)">
                        </div>
                        <div class="showImg" v-if="isShowImg">
                            <img src="@/assets/img/icon_delete.png" class="deleteImg" @click="deleteImg" />
                            <img :src='pictureUrl' class="uploadImg" />
                        </div>
                        <div class="msgStatus">{{upLoadStatus}}</div>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <div class="items">
                        <label class="label" for="">
                            <img class="required" src="@/assets/img/flower_red.png" alt="">
                            状态
                        </label>
                        <el-radio-group v-model="status">
                            <el-radio :label="true">启用</el-radio>
                            <el-radio :label="false">禁用</el-radio>
                        </el-radio-group>
                    </div>
                </el-col>
            </el-row>
            <div class="formBtnList">
                <button class="sureBtn" @click="sureBtn">保存</button>
                <button class="cancelBtn" @click="toCancel">取消</button>
            </div>
        </div>
    </div>
</template>
<script>
import { addLevel, editLevel, getInfos, getRightsList } from './axios.js'
import _axios from '@/tool/http.js'
import { setTimeout } from 'timers';
export default {
    name:'createLevel',
    data(){
        return{
            LvOptionsArr: [1,2,3,4,5,6,7,8,9],
            level:'',
            name:'',
            rights:[],
            growthValueBegin:'',
            growthValueEnd:'',
            status:'',
            isDisabled:false,
            // 编辑缓存的数据
            subData: '',

            pictureUrl:'', //上传的图片
            isShowImg:false,
            isShowUpBtn:true,
            upLoadStatus:'',
            rightsList: [],
        }
    },
    props: ['type'],
    methods:{
        toCancel(){
            this.$router.replace({name:'memberLevel'})
        },
        // 表单验证
        validateData() {
            let regExp = /^[ ]*$/
            let pass = true
            regExp.test(this.level) && (pass = false)
            regExp.test(this.name) && (pass = false)
            regExp.test(this.growthValueBegin) && (pass = false) 
            regExp.test(this.growthValueEnd) && (pass = false)
            regExp.test(this.level) ? this.$refs.level.classList.add('qxz_redInput') : this.$refs.level.classList.remove('qxz_redInput')
            regExp.test(this.name) ? this.$refs.name.classList.add('qxz_redInput') : this.$refs.name.classList.remove('qxz_redInput')
            regExp.test(this.growthValueBegin) ? this.$refs.growthValueBegin.$el.classList.add('qxz_redInput') : this.$refs.growthValueBegin.$el.classList.remove('qxz_redInput')
            regExp.test(this.growthValueEnd) ? this.$refs.growthValueEnd.$el.classList.add('qxz_redInput') : this.$refs.growthValueEnd.$el.classList.remove('qxz_redInput')
            regExp.test(this.status) && (pass = false)
            !this.rights.length && (pass = false)
            !this.pictureUrl.length && (pass = false)
            regExp.test(this.status) && this.$message({
                message: '未勾选状态',
                type: 'warning'
            })
            !this.pictureUrl.length && this.$message({
                message: '未上传图片',
                type: 'warning'
            })
            !this.rights.length && this.$message({
                message: '未勾选会员权益',
                type: 'warning'
            })
            return pass
        },
        //确定新建  表单验证
        sureBtn(){
            if(!this.validateData()) {
                return
            }
            var that = this;
            var rightArr = this.rights;
            var rightString = rightArr.join(",");
            var formObj = {
                level: this.level,
                name: this.name,
                growthValueBegin: this.growthValueBegin,
                growthValueEnd: this.growthValueEnd,
                pictureUrl: this.pictureUrl,
                rights: rightString,
                status: this.status,
            }
            console.log('会员权益',formObj)
            let pass = false
            this.type === 'edit' && Object.keys(formObj).map(ele => {
                formObj[ele] != this.subData[ele] && (pass = true)
            })
            !pass && this.$message({
                type: 'warning',
                message: '没有修改，无需保存'
            })
            this.type === 'edit' && (formObj.id = this.subData.id)
            this.type === 'edit' && pass && editLevel(formObj).then((res)=>{
                console.log('编辑保存',res)
                if(res.data.status == 200){
                    setTimeout(function(){
                        that.$message({
                            message: '编辑等级成功',
                            type: 'success'
                        });
                        that.successCb()
                    },2000)
                    
                }else{
                    that.$message({
                        message: res.data.msg,
                        type: 'warning'
                    });
                }
            })
            this.type === 'create' && addLevel(formObj).then((res)=>{
                if(res.data.status == 200){
                    that.$message({
                        message: '新建等级成功',
                        type: 'success'
                    });
                    this.clearInput()
                    this.successCb()
                }else{
                    that.$message({
                        message: res.data.msg,
                        type: 'warning'
                    });
                }
            })
        },
        // 新增、编辑成功的回调
        successCb() {
            this.$router.replace({name: 'memberLevel'})
        },
        clearInput() {
            this.level = ''
            this.name = ''
            this.rights = []
            this.growthValueBegin = ''
            this.growthValueEnd = ''
            this.status = ''
            this.pictureUrl = '' //上传的图片
            this.isShowImg = false
            this.isShowUpBtn = true
        },
        // 编辑回显
        fillData() {
            let query = this.$route.query;
            query && getInfos(query.key).then(res => {
                if(res.data.status === 200) {
                    console.log('编辑数据回显',res)
                    let result = res.data.result;
                    this.subData = result;
                    this.level = result.level;
                    this.name = result.name;
                    this.name = result.name;
                    let arr = result.rights.split(',')
                    let Arr = []
                    arr.map(ele => {
                        Arr.push(Number(ele))
                    })
                    this.rights = Arr
                    result.pictureUrl && (this.isShowImg = true);
                    result.pictureUrl && (this.isShowUpBtn = false);
                    result.pictureUrl && (this.pictureUrl = result.pictureUrl);
                    this.growthValueBegin = result.growthValueBegin;
                    this.growthValueEnd = result.growthValueEnd;
                    this.status = result.status;
                }else {
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    })
                }
            }).catch(err => {
                console.log('err: ', err)
            })
        },
        // 点击上传
        upfileChange(el){
            var fileObj = el.target.files[0];
            var fileSize = fileObj.size;
            console.log('图片相关信息',el)
            var typeStr = 'image/jpg,image/png,image/bmp,image/jpeg,image/tiff';
            if(typeStr.indexOf(fileObj.type) >0){
                if(fileSize/1024/1024 > 2){
                    //that.upLoadStatus = '图片大小不能超过2M'
                    this.$message({
                        message: '图片大小不能超过2M',
                        type: 'warning'
                    });
                    return;
                }else{
                    var form = new FormData();
                    form.append("file", fileObj);
                    form.append("fileType", typeStr);
                    this.uploadImg(this,form);
                }
            }else{
                this.$message({
                    message: '上传不支持此图片格式',
                    type: 'warning'
                });
            }
            
        },
        // 上传图片
        uploadImg(that,formData) {
            spinner.text = '上传中...'
            that.$ajax({
                method: 'post',
                url: api.domain + '/base/file/uploadOne',
                data:formData
            }).then((res)=>{
                var data = res.data;
                console.log('上传图片',res)
                if(data.status == 200){
                    console.log('上传图片成功了！可喜可贺，喜大普奔',res);
                    that.isShowUpBtn = false;
                    that.isShowImg = true;
                    that.pictureUrl = data.result.url; //图片地址
                    that.$message({
                        message: '图片上传成功',
                        type: 'success'
                    });
                }else{
                    that.$message({
                        message: '图片上传失败',
                        type: 'warning'
                    });
                }
            }).catch((err) => {
                console.log('没成功！死命上传',err);
                that.$message({
                    message: err.data.msg,
                    type: 'warning'
                });
            })
        },
        // 删除图片
        deleteImg(){
            this.isShowUpBtn = true;
            this.isShowImg = false;
            this.pictureUrl = ''
        }
    },
    created(){
        if(this.type === 'edit'){
            this.isDisabled = true
        }else{
            this.isDisabled = false
        }
    },
    activated() {
        this.type === 'edit' && this.fillData()
        getRightsList().then(res => {
            if(res.data.status === 200) {
                this.rightsList = res.data.result
            }
        }).catch(err => {
            console.log('err: ', err)
        })
    }
}
</script>
<style scoped>
@import '../../components/css/viewCommon.css';

.formCreateLevel .el-form-item__label {
    display: inline-block;
    width: 120px;
}
.el-upload--picture-card{
    width:80px;
    height: 80px;
    line-height: 80px;
    border:1px #ddd solid;
    display: inline-block;
}
.el-form-item__error{
    top:40px;
    right:0
}

</style>
<style scoped>
.boxes{
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.optionsField{
    flex: 1;
    align-items: center;
    justify-content: space-between;
}

.formLayout{
    margin: 16px;
    background-color: #fff;
    min-height: 30rem;
    overflow: auto;
    padding: 24px 0;
    border-radius: 8px;
}

/*新添加*/
.createLevel .items{
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    margin-bottom: 24px;
}

.label{
    font-size: 14px;
    min-width: 100px;
    padding-right: 8px;
    text-align: right;
}
.label img{
    margin-bottom: 2px;
}
.createLevel .items .label .required{
    width: 6px;
    height: 6px;
}
.createLevel .items .input-cont{
    height: 32px;
}
/*新添加*/

.inputWidth{
    max-width: 134px;
}
.el-form-item{
    margin-bottom:20px
}
.formBtnList{
    margin-top:170px;
    display: flex;
    justify-content: center;
}
.formBtnList button{
    width: 120px;
	height: 40px;
	border-radius: 20px;
    border:0;
    color:#fff;
    margin:0 8px
}
.formBtnList button:hover{
    cursor: pointer;
}
.cancelBtn{
    background-color:#222
}
.sureBtn{
    background-color:#7e6b5a
}
.el-upload-list__item-actions{
    width: 80px;
    height: 80px;
}
/deep/.el-checkbox{
    margin-left: 0;
    margin-right: 0;
    display: inline-block;
    width: 25%;
    height: 24px;
    min-width:180px;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap
}
/deep/.el-checkbox+.el-checkbox{
    margin-left: 0;
}
/*上传图片*/
.upfile:hover{
    cursor: pointer;
}
.createLevel .detialCell{
    width:80px;
    height:80px;
    font-size:14px;
    border: 1px solid #bbb;
    line-height: 1;
    cursor: pointer;
    margin-left: 6px;
    color:#bbb;
    position:relative;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing:border-box;
    cursor: pointer;
}
.createLevel .detialCell p{
    font-size: 4rem;
}
.createLevel .upfile{
    position: absolute;
    left: 0;
    top: 0;
    width: 80px;
    height: 80px;
    opacity: 0;
    
}
.createLevel .showImg{
    width:80px;
    height:80px;
    position:relative;
}
.createLevel .showImg .deleteImg{
    position: absolute;
    right: -7px;
    top: -7px;
}
.createLevel .showImg .deleteImg:hover{
    cursor: pointer;
}
.createLevel .showImg .uploadImg{
    width:100%;
    height:100%;
}
.createLevel .msgStatus{
    font-size:12px;
    color:red
}

</style>


